package org.zachary.agent.infrastructure.utils;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class HiloGenerator {
    private final String bizType;
    private final int maxLo;
    private int hi = 0;
    private int lo = -1;

    private final JdbcTemplate jdbcTemplate;


    public HiloGenerator(
            @Value("${hilo.biz-type}") String bizType,
            @Value("${hilo.max-lo}") int maxLo,
            JdbcTemplate jdbcTemplate
    ) {
        this.bizType = bizType;
        this.maxLo = maxLo;
        this.jdbcTemplate = jdbcTemplate;
    }


    @Transactional
    public synchronized int generateId() {
        if (lo == -1 || lo >= maxLo) {
            fetchNextHi();
            lo = 0;
        }
        int id=hi * (maxLo + 1) + lo++;
        System.out.println("Hilo算法： "+id);
        return id;
    }

    private void fetchNextHi() {
        Integer currentHi = jdbcTemplate.queryForObject(
                "SELECT next_hi FROM hilo_sequence WHERE sequence_name = ? FOR UPDATE",
                Integer.class, bizType
        );

        if (currentHi != null) {
            int updated = jdbcTemplate.update(
                    "UPDATE hilo_sequence SET next_hi = ? WHERE sequence_name = ?",
                    currentHi + 1, bizType
            );

            if (updated == 0) {
                throw new IllegalStateException("更新序列失败: " + bizType);
            }
            hi = currentHi;
        } else {
            throw new IllegalArgumentException("未找到序列记录: " + bizType);
        }
    }
}